//
//  WebViewController.m
//  Lovelife
//
//  Created by dllo on 15/4/21.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "WebViewController.h"
#import <ShareSDK/ShareSDK.h>
@interface WebViewController ()<UIWebViewDelegate>
@property (nonatomic, retain) UIWebView *webView;
@property (nonatomic, retain) UIActivityIndicatorView *activityIndicatorView;
@property (nonatomic ,retain) UIAlertView *alert;
@property (nonatomic ,retain) NSMutableArray *modelArr;
@property (nonatomic ,retain) UIAlertView *alertDid;

@end

@implementation WebViewController
- (void)dealloc
{
    [_modelArr release];
    [_url release];
    [_titleName release];
    [_webView release];
    [_activityIndicatorView release];
    [_alert release];
    [_alertDid release];
    [super dealloc];
}
-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{

    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
       
        
        NSArray *sandPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        
        NSString *sandBoxPath = [sandPath lastObject];
        
        NSString *storePath = [sandBoxPath stringByAppendingPathComponent:@"itemzero.plist"];
        NSLog(@"%@",storePath);
        self.modelArr = [NSKeyedUnarchiver unarchiveObjectWithFile:storePath];
    }
    return self;

    

}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = self.titleName;

    self.view.backgroundColor = [UIColor whiteColor];
    //1.创建网络请求
    NSURL *url =[NSURL URLWithString:self.url];
    NSURLRequest *request =[NSURLRequest requestWithURL:url];
    self.webView = [[UIWebView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.webView.backgroundColor = [UIColor grayColor];
    //2.设置WebView的代理
    self.webView.delegate = self;
    //伸缩内容适应屏幕尺寸
    self.webView.scalesPageToFit = YES;
    //加载网络请求
    [self.webView loadRequest:request];
    [self.view addSubview:self.webView];
    [_webView release];
    
    
    // 旋转进度轮
    self.activityIndicatorView = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(0.0, 0.0, 100, 100)] ;
    [self.activityIndicatorView setCenter:self.view.center];
    [self.activityIndicatorView setActivityIndicatorViewStyle: UIActivityIndicatorViewStyleGray];
    [self.view addSubview:self.activityIndicatorView];
    [_activityIndicatorView release];
    
   
 
    UIBarButtonItem *fenxiang = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"btn_share_bg"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(shareAction:)];
    
    UIBarButtonItem *shoucang = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"btn_menu_bg"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(shoucangAction:)];
    
    
    self.navigationItem.rightBarButtonItems = @[shoucang,fenxiang];
    
    
}

-(void)shareAction:(UIBarButtonItem *)sander
{

    NSLog(@"123");
    NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"ShareSDK" ofType:@"png"];
    
    //构造分享内容
    id<ISSContent> publishContent = [ShareSDK content:@"分享内容"
                                       defaultContent:@"测试一下"
                                                image:[ShareSDK imageWithPath:imagePath]
                                                title:@"ShareSDK"
                                                  url:@"http://www.mob.com"
                                          description:@"这是一条测试信息"
                                            mediaType:SSPublishContentMediaTypeNews];
    //创建弹出菜单容器
    id<ISSContainer> container = [ShareSDK container];
    [container setIPadContainerWithView:self.view arrowDirect:UIPopoverArrowDirectionUp];
    
    //弹出分享菜单
    [ShareSDK showShareActionSheet:container
                         shareList:nil
                           content:publishContent
                     statusBarTips:YES
                       authOptions:nil
                      shareOptions:nil
                            result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
                                
                                if (state == SSResponseStateSuccess)
                                {
                                    NSLog(NSLocalizedString(@"TEXT_ShARE_SUC", @"分享成功"));
                                }
                                else if (state == SSResponseStateFail)
                                {
                                    NSLog(NSLocalizedString(@"TEXT_ShARE_FAI", @"分享失败,错误码:%d,错误描述:%@"), [error errorCode], [error errorDescription]);
                                }
                            }];

}

-(void)shoucangAction:(UIBarButtonItem *)sander
{
    
    NSLog(@"shoucang");
    BOOL isSub = NO;
    if (!self.modelArr) {
        self.modelArr = [NSMutableArray array];
        NSLog(@"%ld",self.modelArr.count);
    }
    NSLog(@"数组个数%ld",self.modelArr.count);
    
     if (self.modelArr.count > 0) {
        for (NSInteger i = 0; i < self.modelArr.count; i++) {
            
            
            ItemZeroModel *zero = self.modelArr[i];
            if ([zero.title isEqualToString:self.model.title] ) {
                
                NSLog(@"1231456");
                NSLog(@"%@--%@",zero.title,self.model.title);
                isSub = YES;
                
                break;
            }else
            {
                isSub = NO;
            
            }
        }
        if (isSub == YES) {
            
            [self addFail];
            
        }else if (isSub == NO)
        {
            
            [self addFile];
            
        }
    }else if (self.modelArr.count == 0)
    {
        NSLog(@"qweqwr");
        [self addFile];
    
    }
    
    

}
-(void)addFile
{
    
    [self.modelArr addObject:self.model];
    
    NSArray *sandPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *sandBoxPath = [sandPath lastObject];
    
    NSLog(@"%@",sandBoxPath);
    
    NSString *storePath = [sandBoxPath stringByAppendingPathComponent:@"itemzero.plist"];
    
    [NSKeyedArchiver archiveRootObject:self.modelArr toFile:storePath];
    
    self.alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"收藏成功" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
    [self.alert show];
    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(performDismiss) userInfo:nil repeats:NO];
    [_alert release];
    

}
-(void)performDismiss
{
    
    [self.alert dismissWithClickedButtonIndex:0 animated:NO];
    
}

-(void)addFail
{
    self.alertDid = [[UIAlertView alloc]initWithTitle:@"提示" message:@"已被收藏过" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [self.alertDid show];
    
    [_alertDid release];
    
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        [NSTimer scheduledTimerWithTimeInterval:0 target:self selector:@selector(click) userInfo:nil repeats:NO];
    }
    
    
}

-(void)click
{
    [self.alertDid dismissWithClickedButtonIndex:0 animated:NO];
    
    
}



// WebView开始加载资源的时候调用（开始发送请求）
- (void)webViewDidStartLoad:(UIWebView *)webView
{
    [self.activityIndicatorView startAnimating] ;
}
// WebView加载完毕的时候调用（请求完毕）
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    NSString *meta = [NSString stringWithFormat:@"var ab = document.getElementById(\"bookmark\"); ab.firstChild.nodeValue = \"做法\";"];
    [webView stringByEvaluatingJavaScriptFromString:meta];
    [self.activityIndicatorView stopAnimating];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
